package com.ehi.common.config;

import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.ReloadingFileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Parameters;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.configuration2.reloading.PeriodicReloadingTrigger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.concurrent.TimeUnit;

/**
 * Created by portz on 7/7/2017.
 */

@Component
public class ConfigProperties {
    private static final Logger LOGGER = LoggerFactory.getLogger(ConfigProperties.class);
    /**
     * refresh every 15 minutes
     */
    private static final long DELAY_MINUTES = 15;
    private ReloadingFileBasedConfigurationBuilder<PropertiesConfiguration> builder;

    @PostConstruct
    private void init() {
        StringBuffer propertiesPath = new StringBuffer(32);
        propertiesPath
            .append(System.getProperty("ext.props.path"))
            .append(File.separator)
            .append("application.properties");

        Parameters params = new Parameters();
        // Read data from this file
        File propertiesFile = new File(propertiesPath.toString());
        LOGGER.info("application properties exists={}, file={}", propertiesFile.exists(), propertiesFile.getAbsolutePath());
        if (!propertiesFile.exists()) {
            throw new RuntimeException("Application properties file not exist, path=" + propertiesFile.getAbsolutePath());
        }
        builder = new ReloadingFileBasedConfigurationBuilder<PropertiesConfiguration>(PropertiesConfiguration.class)
            .configure(params.fileBased()
                .setFile(propertiesFile));
        PeriodicReloadingTrigger trigger = new PeriodicReloadingTrigger(builder.getReloadingController(),
            null, DELAY_MINUTES, TimeUnit.MINUTES);
        trigger.start();
    }

    /**
     * return null if the 'key' does not exist
     */
    public String get(String key) {
        return this.checkProperty(key, null);
    }

    /**
     * return defaultValue if the 'key' does not exist
     */
    public String get(String key, String defaultValue) {
        return this.checkProperty(key, defaultValue);
    }

    private String checkProperty(String key, String defaultValue) {
        PropertiesConfiguration configuration = null;
        try {
            configuration = builder.getConfiguration();
        } catch (ConfigurationException e) {
            LOGGER.error("Get application properties fail", e);
            return defaultValue;
        }
        if (configuration != null && configuration.containsKey(key)) {
            return (String) configuration.getProperty(key);
        }
        return defaultValue;
    }

}
